What is immer?
Immer is a package that allows you to work with immutable state in a more convenient way. It uses a copy-on-write mechanism to ensure that the original state is not mutated. Instead, Immer produces a new updated state based on the changes made within a 'produce' function. This approach simplifies the process of updating immutable data structures, especially in the context of modern JavaScript frameworks and libraries such as React and Redux.
What are immer's main functionalities?
Creating the next immutable state by modifying the current state
This feature allows you to pass a base state and a producer function to the 'produce' function. Within the producer function, you can mutate the draft state as if it were mutable. Immer takes care of applying the changes to produce the next immutable state.
import produce from 'immer';
const baseState = [
{todo: 'Learn typescript', done: true},
{todo: 'Try immer', done: false}
];
const nextState = produce(baseState, draftState => {
draftState.push({todo: 'Tweet about it'});
draftState[1].done = true;
});
Working with nested structures
Immer can handle deeply nested structures with ease. You can update deeply nested properties without the need to manually copy every level of the structure.
import produce from 'immer';
const baseState = {
user: {
name: 'Michele',
age: 33,
todos: [
{title: 'Tweet about it', done: false}
]
}
};
const nextState = produce(baseState, draftState => {
draftState.user.age = 34;
draftState.user.todos[0].done = true;
});
Currying
Immer supports currying, which means you can predefine a producer function and then apply it to different states. This is useful for creating reusable state transformers.
import produce from 'immer';
const baseState = {counter: 0};
const increment = produce(draft => {
draft.counter++;
});
const nextState = increment(baseState);
Other packages similar to immer
immutable
Immutable.js is a library by Facebook that provides persistent immutable data structures. Unlike Immer, which allows you to write mutable code that gets converted to immutable updates, Immutable.js requires you to use specific methods to update data structures. It offers a wide range of data structures like List, Map, Set, etc.
mori
Mori is a library that brings Clojure's persistent data structures to JavaScript. It is similar to Immutable.js in that it provides a variety of immutable data structures and functional programming utilities. Mori's API is quite different from JavaScript's native arrays and objects, which can have a steeper learning curve compared to Immer.
seamless-immutable
Seamless-immutable is a library that provides immutability for your data structures without drastically changing the syntax of standard JavaScript objects and arrays. It is less powerful than Immer in terms of handling complex updates and nested structures but offers a simpler and more familiar API for those who prefer to work with plain JavaScript objects.